package com.jxud.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.jxud.enums.SensitiveTypeEnum;
import com.jxud.utils.DesensitizationContextHolder;
import com.jxud.utils.SensitiveData;

import java.io.IOException;
import java.util.regex.Pattern;

//订单信息脱敏 核心逻辑
public class SensitiveDataSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private final SensitiveTypeEnum type;

    public SensitiveDataSerializer() {
        this(null);
    }

    public SensitiveDataSerializer(SensitiveTypeEnum type) {
        this.type = type;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }

        // 检查上下文，判断是否需要脱敏
        if (DesensitizationContextHolder.isDesensitizationDisabled()) {
            gen.writeString(value); // 不脱敏，直接返回原始值
        } else {
            gen.writeString(mask(value, type)); // 执行脱敏
        }
    }

    private String mask(String value, SensitiveTypeEnum type) {
        if (value.isEmpty()) {
            return value;
        }

        return switch (type) {
            case NAME -> maskName(value);
            case MOBILES -> maskMobile(value);
            case ADDRESS -> maskAddress(value);
            default -> value;
        };
    }

    private String maskName(String value) {
        if (value == null || value.isEmpty()) {
            return "*";
        }
        int len = value.length();
        if (len == 1) {
            return "*";
        }
        // 保留第一个字符，其余全部替换为 *
        return value.charAt(0) + "*".repeat(len - 1);
    }

    private String maskMobile(String value) {
        if (value == null || value.isEmpty()) {
            return value;
        }

        // 匹配 11 位手机号 + 可选的 "-分机号"（允许数字、字母、符号等）
        // 比如：18547232703, 18547232703-1536, 18547232703-ext123
        var pattern = "(\\d{11})(-.+)?";
        var matcher = Pattern.compile(pattern).matcher(value);

        if (matcher.matches()) {
            String mobile = matcher.group(1); // 11位手机号
            String extension = matcher.group(2); // 分机号部分（含 '-'），可能为 null

            // 脱敏手机号：前3后4，中间4星
            String maskedMobile = mobile.substring(0, 3) + "****" + mobile.substring(7);

            // 返回脱敏手机号 + 原始分机号
            return extension != null ? maskedMobile + extension : maskedMobile;
        }

        // 不符合规则的，原样返回
        return value;
    }

    private String maskAddress(String value) {
        if (value == null || value.isEmpty()) {
            return "";
        }
        int len = value.length();
        if (len <= 2) {
            return "*".repeat(len); // 或统一返回 "**" 如果最小打码长度为2
        }
        return value.substring(0, 2) + "*".repeat(len - 2);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property == null) {
            return this;
        }

        SensitiveData annotation = property.getAnnotation(SensitiveData.class);
        if (annotation != null && String.class.isAssignableFrom(property.getType().getRawClass())) {
            return new SensitiveDataSerializer(annotation.type());
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
